package org.example.pingpong.interceptors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.pingpong.domain.po.User;
import org.example.pingpong.service.UserService;
import org.example.pingpong.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class PowerInterceptors implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("Authorization");
        try {
            if (token == null || token.isEmpty() || redisTemplate.opsForValue().get(token) == null)
                throw new RuntimeException();
            Map<String, Object> map = JwtUtil.parseToken(token);
            Integer userId = (Integer) map.get("id");
            System.out.println(userId);
            if (redisTemplate.opsForValue().get("#*admin*#") == null) {
                redisTemplate.opsForValue().set("#*admin*#", userService.getOne(new LambdaQueryWrapper<User>().eq(User::getPower, 1)).getId(), 30, TimeUnit.MINUTES);
            }
            if (userId.compareTo((Integer) redisTemplate.opsForValue().get("#*admin*#")) == 0) return true;
        } catch (RuntimeException e) {
            response.setStatus(401);
            return false;
        }
        response.setStatus(401);
        return false;
    }
}
